package com.czsth.admin.files;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

//http://blog.csdn.net/itmyhome1990/article/details/40374843
//http://dove19900520.iteye.com/blog/1915760
public class ImgUploadAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private String err = "";
    private String msg;              //返回信息  
    private File upload_file;           //上传文件
    private String original_filename; //文件名

    public String upload() {
        //获取response、request对象  
        ActionContext ac = ActionContext.getContext();
        HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        String saveRealFilePath = ServletActionContext.getServletContext().getRealPath("/upload");
        File fileDir = new File(saveRealFilePath);
        if (!fileDir.exists()) { //如果不存在 则创建   
            fileDir.mkdirs();
        }
        File savefile;
        savefile = new File(saveRealFilePath + "/" + original_filename);
        try {
            FileUtils.copyFile(upload_file, savefile);
        } catch (IOException e) {
            err = "错误" + e.getMessage();
            e.printStackTrace();
        }
        String file_Name = request.getContextPath() + "/upload/" + original_filename;

//        {
//            "success": true/false,
//                "msg": "上传失败信息", # 可选
//            "file_path": "[real file path]"
//        }

        msg = "{\"success\":\"" + true + "\",\"file_path\":\"" + file_Name + "\"}";
        out.print(msg); //返回msg信息

        return NONE;
    }

    public String getErr() {
        return err;
    }

    public void setErr(String err) {
        this.err = err;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public File getUpload_file() {
        return upload_file;
    }

    public void setUpload_file(File upload_file) {
        this.upload_file = upload_file;
    }

    public String getOriginal_filename() {
        return original_filename;
    }

    public void setOriginal_filename(String original_filename) {
        this.original_filename = original_filename;
    }
}  